package com.xingdata.jjxc.m.accessibility;

import jar.MessageManager;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.enty.NotificationEntity;
import com.xingdata.jjxc.utils.Hud_Panid;
import com.xingdata.jjxc.utils.SystemInfo;

public class TaskBackService extends AccessibilityService implements
		TextToSpeech.OnInitListener {
	private TextToSpeech speech;
	private boolean mTextToSpeechInitialized = false;
	// private UartService service;
	private static String TAG = "TaskBackService";
	private HashMap<String, String> typeMap = new HashMap<String, String>();

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		if (event.getPackageName() == null) {
			return;
		}
		// 有的手机返回包名太变态了后面有空格
		String strPackageName = event.getPackageName().toString().trim();
		Log.i(TAG, "消息类型:" + "packetName " + strPackageName);

		if (SystemInfo.messageCodeMap == null) {
			Log.i(TAG, "消息类型匹配错误");
		}
		if (!mTextToSpeechInitialized) {
			return;
		}
		if (SystemInfo.messageCodeMap.containsKey(strPackageName)) {
			NotificationEntity mEntity = SystemInfo.messageCodeMap
					.get(strPackageName);
			String strEvent = event.getText().toString();
			String strMessage = "";
			strEvent = strEvent.replaceAll(",", "，");
			String body = "";
			int index = strEvent.indexOf(": ");
			if (index > -1) {
				body = strEvent.substring(1, index);
				mEntity.setMessageForm(body);
				strMessage = strEvent.substring(1, strEvent.length() - 1);
				strMessage = strMessage.replace("/", "");
				mEntity.setMessage(strMessage.substring(index + 1,
						strMessage.length()));
				
				if (mEntity.getMessage()!=null&&mEntity.getMessage().length()>75) {
					mEntity.setMessage(mEntity.getMessage().substring(0,72)+"...");
				}
				
				mEntity.setType(typeMap.get(strPackageName));
				//短信 0 微信1 QQ2
				Log.i(TAG, mEntity.getMessage());
				MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),
						new RequestEntity(JSON.toJSONString(mEntity),
								InstructionSet.INSTRUCTION_AUTH_MESSAGE_TO_HUD
										+ ""));
			}

			// mEntity.setType(type);

			// if (getUartService() != null && index > -1) {
			// // 0x05 0x32 \t 昵称 \t 内容（昵称+：+内容） 0x0d 0x0a
			// bs = new ArrayList<byte[]>();
			// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithMessage);
			// bs.add(getMessageCode(mEntity.getMessageCode()));
			// bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
			// body = strEvent.substring(1, index);
			// strMessage = strEvent.substring(1, strEvent.length() - 1);
			// strMessage = strMessage.replace("/", "");
			// try {
			// // QQ 微信
			// bs.add(mEntity.getName().getBytes("utf-8"));
			// // \t
//			 bs.add(Hud_Panid.ZXSendHudDataBeforTypeWithFeedBackNewline);
			// // 内容
			// bs.add(strMessage.getBytes("utf-8"));
			// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd1);
			// bs.add(Hud_Panid.ZXSendHudDataBeforCodeWithCallUPEnd2);
			// } catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			// }
			// Log.i(TAG, "body: " + body + " message: " + strMessage);
			// Consumer.getInstance().add(new MessageTask(service, "",
			// StringUtil
			// .ArrayBytesCopy(bs)));
			//
			// }
		}
	}

	private byte[] getMessageCode(String messageCode) {
		byte[] b = null;
		int code = Integer.parseInt(messageCode);
		switch (code) {
		// 短信 0x30
		case 0:
			b = Hud_Panid.ZXSendHudDataBeforTypeWithCallUp;
			break;
		// qq 0x32
		case 1:
			b = Hud_Panid.ZXSendHudDataBeforTypeWithQQ;
			break;
		// 微信 0X33
		case 2:
			b = Hud_Panid.ZXSendHudDataBeforTypeWithWeiXin;
			break;
		// 旺信
		case 3:
			b = Hud_Panid.ZXSendHudDataBeforTypeWithWangXin;
			break;
		default:
			break;
		}
		return b;

	}

	// private UartService getUartService() {
	// if (service == null) {
	// service = BluetoothGattTools.getUartService();
	// }
	// return service;
	//
	// }

	@Override
	public void onInterrupt() {
		System.out.println("-----------interrupt");
	}

	@Override
	public void onServiceConnected() {
		System.out.println("----------connect");
		speech = new TextToSpeech(getApplicationContext(), this);
		AccessibilityServiceInfo info = new AccessibilityServiceInfo();
		info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
		info.notificationTimeout = 100;
		info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
		String packageNames[] = { "com.android.contacts", "com.tencent.mm",
				"com.tencent.mobileqq" };
		info.packageNames = packageNames;
		setServiceInfo(info);
		for (int i = 0; i < info.packageNames.length; i++) {
			typeMap.put(info.packageNames[i], i + "");
		}
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			speech.setLanguage(Locale.US);
			mTextToSpeechInitialized = true;
		}
	}
}
